<?php

namespace app\admin\controller;

use think\Db;
use \app\admin\model\Product as ProductModel;
use \app\admin\model\Logistics as LogisticsModel;

class Amazonorder extends Main
{
    //订单状态
    public $order_status = array(
        1 => '未付款',
        2 => '取消',
        3 => '审核',
        4 => '找货',
        5 => '缺货',
        6 => '配货',
        7 => '待发货',
        8 => '已发货',
        9 => '交付',
        10 => '问题',
        11 => '补发',
        12 => '退货',
        13 => '备查',
        14 => 'FBA'
    );
    //订单详情中状态
    public $detail_order = array(
        1 => '未付款',
        2 => '取消',
        3 => '审核',
        7 => '待发货',
        8 => '已发货',
        9 => '交付',
        12 => '退货',
        14 => 'FBA'
    );
    public $detail_good = array(
        4 => '找货',
        5 => '缺货',
        6 => '配货',
        10 => '问题',
        11 => '补发',
        13 => '备查'

    );


    public $goods_money = 0;//订单商品成本

    public $productModel = '';

    /**
     * 亚马逊列表
     */
    public function amazon()
    {
        if (checkHeadOfficeManage()) {//总公司管理员，跳转选子公司页面
            $this->adminAmazon();
            return $this->fetch('adminamazon');
        } else {
            $this->yuanAmazon();
            return $this->fetch('amazon');
        }
    }

    /**
     * 普通员工亚马逊订单列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function yuanAmazon(){
        $where = [];
        $where1 = [];
        $product = [];
        $where['company_id'] = iget('company_id') ? iget('company_id') : isession('company_id');
        $unit = sget('unit') ? sget('unit') : 'CNY';
        //获取当前用户下的有效店铺
        $store = $this->getStoreByUser(1, $where['company_id']);
        $store_id = join(',', array_column($store, 'id'));
        $where['shop_id'] = ['in', $store_id];
        //订单编号
        get('order_no') && $where['order_no'] = ['like', '%' . get('order_no') . '%'];
        get('order_status') && $where['order_status'] = get('order_status');
        get('start') && $where1['create_time'] = ['>=', strtotime(get('start') . " 00:00:00")];
        get('shop_id') && $where1['shop_id'] = get('shop_id');
        get('end') && $where['create_time'] = ['<=', strtotime(get('end') . " 23:59:59")];
        $data = Db::name('amazon_order')
            ->where($where)
            ->where($where1)
            ->order('create_time desc')
            ->paginate(30, false, ['query' =>
                [
                    'order_no' => get('order_no'),
                    'order_status' => get('order_status'),
                    'start' => get('start'),
                    'end' => get('end'),
                    'shop_id' => get('shop_id'),
                    'company_id' => iget('company_id'),
                    'unit' => $unit
                ]]);

        $list = $data->all();
        if (checkArr($list)) {
            //获取所有订单id
            $order_ids = array_column($list, 'id');

            //获取订单下有图片url的商品
            $where2['url'] = ['neq', ''];
            $where2['order_id'] = ['in', join(',', $order_ids)];
            $product = Db::name('amazon_order_goods')
                ->field('order_id,url')
                ->where($where2)
                ->group('order_id')
                ->select();
            checkArr($product) && $product = arrayCombine($product, 'order_id');
        }

        //总价
        $total = Db::name('amazon_order')->where($where)->where($where1)->sum('order_total');
        //运费
        $shipping_money = Db::name('amazon_order')->where($where)->where($where1)->sum('shipping_money');
        //成本
        $goods_money = Db::name('amazon_order')->where($where)->where($where1)->sum('goods_money');
        //手续费
        $expend_fee = Db::name('amazon_order')->where($where)->where($where1)->sum('expend_fee');

        $profit = $total - $shipping_money - $goods_money - $expend_fee;

        if ($unit != 'CNY') {
            $rate = $this->getRate($unit);
            $total = cutNum($total * $rate[$unit]['rate'], 2);
            $shipping_money = cutNum($shipping_money * $rate[$unit]['rate'], 2);
            $goods_money = cutNum($goods_money * $rate[$unit]['rate'], 2);
            $expend_fee = cutNum($expend_fee * $rate[$unit]['rate'], 2);
            $profit = cutNum($profit * $rate[$unit]['rate'], 2);
        }

        $this->assign('total', $total);
        $this->assign('shipping_money', $shipping_money);
        $this->assign('goods_money', $goods_money);
        $this->assign('expend_fee', $expend_fee);
        $this->assign('profit', $profit);

        $this->assign('product', $product);
        $this->assign('unit', $this->getDictionary('unit'));
        $this->assign('order_status', $this->order_status);
        $this->assign('store', $store);
        $this->assign('orders', $data);
    }

    /**
     * 总管理员列表页
     */
    public function adminAmazon()
    {
        $where = [];
        $where1 = [];
        $product = [];
        $company_id = iget('company_id');
        $company_id && $where['company_id'] = $company_id;
        $unit = sget('unit') ? sget('unit') : 'CNY';
        //订单编号
        get('order_no') && $where['order_no'] = ['like', '%' . get('order_no') . '%'];
        get('order_status') && $where['order_status'] = get('order_status');
        get('start') && $where1['create_time'] = ['>=', strtotime(get('start') . " 00:00:00")];
        get('end') && $where['create_time'] = ['<=', strtotime(get('end') . " 23:59:59")];
        $data = Db::name('amazon_order')
            ->where($where)
            ->where($where1)
            ->order('create_time desc')
            ->paginate(30, false, ['query' =>
                [
                    'order_no' => get('order_no'),
                    'order_status' => get('order_status'),
                    'start' => get('start'),
                    'end' => get('end'),
                    'company_id' => $company_id,
                    'unit' => $unit
                ]]);

        $list = $data->all();
        if (checkArr($list)) {
            //获取所有订单id
            $order_ids = array_column($list, 'id');

            //获取订单下有图片url的商品
            $where2['url'] = ['neq', ''];
            $where2['order_id'] = ['in', join(',', $order_ids)];
            $product = Db::name('amazon_order_goods')
                ->field('order_id,url')
                ->where($where2)
                ->group('order_id')
                ->select();
            checkArr($product) && $product = arrayCombine($product, 'order_id');
        }

        //总价
        $total = Db::name('amazon_order')->where($where)->where($where1)->sum('order_total');
        //运费
        $shipping_money = Db::name('amazon_order')->where($where)->where($where1)->sum('shipping_money');
        //成本
        $goods_money = Db::name('amazon_order')->where($where)->where($where1)->sum('goods_money');
        //手续费
        $expend_fee = Db::name('amazon_order')->where($where)->where($where1)->sum('expend_fee');

        $profit = $total - $shipping_money - $goods_money - $expend_fee;

        if ($unit != 'CNY') {
            $rate = $this->getRate($unit);
            $total = cutNum($total * $rate[$unit]['rate'], 2);
            $shipping_money = cutNum($shipping_money * $rate[$unit]['rate'], 2);
            $goods_money = cutNum($goods_money * $rate[$unit]['rate'], 2);
            $expend_fee = cutNum($expend_fee * $rate[$unit]['rate'], 2);
            $profit = cutNum($profit * $rate[$unit]['rate'], 2);
        }
        //获取当全部亚马逊有效店铺
        $store = DB::name('amazon_store')->field('id,nation,nation_short')->where('status', 1)->select();
        checkArr($store) && $store = arrayCombine($store, 'id');
        $this->assign('store', $store);
        $this->assign('total', $total);
        $this->assign('shipping_money', $shipping_money);
        $this->assign('goods_money', $goods_money);
        $this->assign('expend_fee', $expend_fee);
        $this->assign('profit', $profit);
        //获取全部公司信息
        $companys = DB::name('company')->field('id,name')->select();
        checkArr($companys) && $companys = arrayCombine($companys, 'id');
        $this->assign('companys', $companys);

        $this->assign('product', $product);
        $this->assign('unit', $this->getDictionary('unit'));
        $this->assign('order_status', $this->order_status);
        $this->assign('orders', $data);
    }

    /**
     * 亚马逊订单详情
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function amazonInfo($id)
    {
        //订单信息
        $order = Db::name('amazon_order')
            ->where('id', $id)
            ->find();
        if (!checkArr($order)) {
            $this->error('当前订单不存在');
        }
        //查找店铺信息
        $store = DB::name('amazon_store')->where('id', $order['shop_id'])->find();

        $company_id = iget('company_id') ? iget('company_id') : isession('company_id');


        if ($order['is_good'] == 1) {//未抓取过数据
            $this->productModel = new ProductModel();
            $this->orderItems($order, $store, $company_id);
        }

        //订单下的产品信息
        $orderGoods = Db::name('amazon_order_goods')
            ->where('order_id', $id)
            ->select();

        //找货状态
        $look_status = 1;
        if (($order['is_good'] == 2) && checkArr($orderGoods)) {
            $goods_money = 0;
            foreach ($orderGoods as $value) {
                $value['good_status'] == 7 && $look_status = 2;
                $goods_money = $goods_money + $value['cost_price'];
            }
            if ($goods_money > 0) {
                $updateData['goods_money'] = $goods_money;
                $num = $order['order_total'] - $goods_money;
                $updateData['profit'] = $num > 0 ? $num : 0;
                Db::name('amazon_order')->where('id', $id)->update($updateData);
            }
        }

        //查找订单备注信息
        $orderRemarks = Db::name('amazon_order_remark')
            ->where('order_id', $id)
            ->order(['timestamp' => 'desc'])
            ->select();
        //获取订单操作日志
        $orderAction = Db::name('amazon_order_action')
            ->where('order_id', $id)
            ->order(['action_time' => 'desc'])
            ->select();

        $this->assign('store', $store);
        $this->assign('look_status', $look_status);
        $this->assign('order_status', $this->order_status);
        $this->assign('detail_order', $this->detail_order);
        $this->assign('detail_good', $this->detail_good);
        $this->assign('order', $order);
        $this->assign('orderGoods', $orderGoods);
        $this->assign('orderRemarks', $orderRemarks);
        $this->assign('orderAction', $orderAction);
        return $this->fetch('amazonInfo');
    }

    /**
     * 抓取订单下的商品信息
     * @param $order
     * @param $store
     * @param $company_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function orderItems($order, $store, $company_id)
    {
        $params = array(
            'AWSAccessKeyId' => $store['aws_access_key'],
            'Action' => "ListOrderItems",
            'SellerId' => $store['seller_id'],
            'SignatureMethod' => "HmacSHA256",
            'SignatureVersion' => "2",
            'Timestamp' => gmdate("Y-m-d\TH:i:s\Z", time()),
            'Version' => "2013-09-01",
            'AmazonOrderId' => $order['order_no']
        );
        $url_parts = array();
        foreach (array_keys($params) as $key) {
            $url_parts[] = $key . "=" . str_replace('%7E', '~', rawurlencode($params[$key]));
        }

        sort($url_parts);
        $url_string = implode("&", $url_parts);
        $string_to_sign = "GET\nmws.amazonservices.in\n/Orders/2013-09-01\n" . $url_string;

        $signature = hash_hmac("sha256", $string_to_sign, $store['secret_key'], TRUE);

        $signature = urlencode(base64_encode($signature));

        $url = "https://mws.amazonservices.in/Orders/2013-09-01" . '?' . $url_string . "&Signature=" . $signature;
        $content = request_get($url);
        if ($content == '') {
            $this->error('获取超时，请重试');
        }
        //获取商品
        $orderGoods = xmlToArray($content);

        //订单中存在商品
        if (isset($orderGoods['ListOrderItemsResult']['OrderItems'])) {
            $this->goods_money = $order['goods_money'];
            foreach ($orderGoods['ListOrderItemsResult']['OrderItems'] as $key => $value) {
                $this->insertOrderGood($value, $order, $store, $company_id);
            }
            //商品存在下一页
            if (isset($orderGoods['ListOrderItemsResult']['NextToken'])) {
                $this->insertNextOrderGood($orderGoods['ListOrderItemsResult']['NextToken'], $store, $company_id);
            }

            Db::name('amazon_order')->where('id', $order['id'])->update(['goods_money' => $this->goods_money, 'is_good' => 2]);
        }
        return true;
    }

    /**
     * 获取下一页订单商品信息
     * @param $nextToken
     * @param $store
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function insertNextOrderGood($nextToken, $store, $company_id)
    {
        $params = array(
            'AWSAccessKeyId' => $store['aws_access_key'],
            'Action' => "ListOrderItemsByNextToken",
            'SellerId' => $store['seller_id'],
            'SignatureMethod' => "HmacSHA256",
            'SignatureVersion' => "2",
            'Timestamp' => gmdate("Y-m-d\TH:i:s\Z", time()),
            'Version' => "2013-09-01",
            'NextToken' => $nextToken
        );
        $url_parts = array();
        foreach (array_keys($params) as $key) {
            $url_parts[] = $key . "=" . str_replace('%7E', '~', rawurlencode($params[$key]));
        }

        sort($url_parts);
        $url_string = implode("&", $url_parts);
        $string_to_sign = "GET\nmws.amazonservices.in\n/Orders/2013-09-01\n" . $url_string;

        $signature = hash_hmac("sha256", $string_to_sign, $store['secret_key'], TRUE);

        $signature = urlencode(base64_encode($signature));

        $url = "https://mws.amazonservices.in/Orders/2013-09-01" . '?' . $url_string . "&Signature=" . $signature;
        $content = request_get($url);
        if ($content == '') {
            $this->error('获取超时，请重试');
        }
        //获取商品
        $orderGoods = xmlToArray($content);
        if (isset($orderGoods['ListOrderItemsByNextTokenResult']['OrderItems'])) {
            foreach ($orderGoods['ListOrdersByNextTokenResult']['OrderItems'] as $key => $value) {
                $insertData[] = $this->insertOrderGood($value, $store, $store, $company_id);
            }
            //存在下一页
            if (isset($orderGoods['ListOrdersByNextTokenResult']['NextToken'])) {
                $this->insertNextOrderGood($orderGoods['ListOrdersByNextTokenResult']['NextToken'], $store, $company_id);
            }
        }
        return true;
    }

    /**
     * 抓取数据插入订单商品表
     * @param $data
     * @param $order
     * @param $store
     * @param $company_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function insertOrderGood($data, $order, $store, $company_id)
    {
        //订单商品去重
        $where['asin'] = $data['ASIN'];
        $where['order_id'] = $order['id'];
        $res = Db::name('amazon_order_goods')->where($where)->find();
        if (checkArr($res)) {
            return true;
        }
        //查询商品库中是否存在该商品
        $good = $this->productModel->getGoodBySku($data['SellerSKU'], $company_id);
        if (checkArr($good)) {//本地库中存在该商品，匹配关联插入订单商品库
            $insertData['order_id'] = $order['id'];
            $insertData['order_no'] = $order['order_no'];
            $insertData['goods_name'] = $data['Title'];
            $insertData['asin'] = $data['ASIN'];
            $insertData['order_item_id'] = $data['OrderItemId'];
            $insertData['guid'] = $good['guid'];
            $insertData['price'] = $good['price'];
            $insertData['cost_price'] = $good['cost'];
            $insertData['num'] = $data['ProductInfo']['NumberOfItems'];
            $insertData['goods_money'] = isset($data['ItemPrice']['Amount']) ? $data['ItemPrice']['Amount'] : 0;
            $insertData['lang'] = 'moren';
            $insertData['coin'] = isset($data['ItemPrice']['CurrencyCode']) ? $data['ItemPrice']['CurrencyCode'] : '';
            $insertData['good_status'] = $order['order_status'];
            $insertData['url'] = $this->getOrderGoodImgUrl($store, $data['ASIN']);
            $this->goods_money = $this->goods_money + $good['cost'];
            Db::name('amazon_order_goods')->insert($insertData);
        } else {//商品库中暂无此商品
            $insertData['order_id'] = $order['id'];
            $insertData['order_no'] = $order['order_no'];
            $insertData['goods_name'] = $data['Title'];
            $insertData['asin'] = $data['ASIN'];
            $insertData['order_item_id'] = $data['OrderItemId'];
            $insertData['guid'] = '';
            $insertData['cost_price'] = 0;
            $insertData['num'] = $data['ProductInfo']['NumberOfItems'];
            $insertData['goods_money'] = isset($data['ItemPrice']['Amount']) ? $data['ItemPrice']['Amount'] : 0;
            $insertData['lang'] = 'moren';
            $insertData['coin'] = isset($data['ItemPrice']['CurrencyCode']) ? $data['ItemPrice']['CurrencyCode'] : '';
            $insertData['good_status'] = $order['order_status'];
            $insertData['price'] = $insertData['goods_money'] / $insertData['num'];//商品单价
            $insertData['url'] = $this->getOrderGoodImgUrl($store, $data['ASIN']);
            Db::name('amazon_order_goods')->insert($insertData);
        }
        return true;
    }

    /**
     * 获取商品图片地址
     * @param $store
     * @param $asin
     * @return mixed
     */
    public function getOrderGoodImgUrl($store, $asin)
    {
        $params = array(
            'AWSAccessKeyId' => $store['aws_access_key'],
            'Action' => "GetMatchingProduct",
            'SellerId' => $store['seller_id'],
            'SignatureMethod' => "HmacSHA256",
            'SignatureVersion' => "2",
            'Timestamp' => gmdate("Y-m-d\TH:i:s\Z", time()),
            'Version' => "2011-10-01",
            'MarketplaceId' => $store['marketplace'],
            'ASINList.ASIN.1' => $asin,
        );
        $url_parts = array();
        foreach (array_keys($params) as $key) {
            $url_parts[] = $key . "=" . str_replace('%7E', '~', rawurlencode($params[$key]));
        }

        sort($url_parts);
        $url_string = implode("&", $url_parts);
        $string_to_sign = "GET\nmws.amazonservices.in\n/Products/2011-10-01\n" . $url_string;

        $signature = hash_hmac("sha256", $string_to_sign, $store['secret_key'], TRUE);

        $signature = urlencode(base64_encode($signature));

        $url = "https://mws.amazonservices.in/Products/2011-10-01" . '?' . $url_string . "&Signature=" . $signature;
        $content = request_get($url);
        if ($content == '') {
            $this->error('获取超时，请重试');
        }
        preg_match_all("/<ns2:URL>(.*)<\/ns2:URL>/U", $content, $pat_array);
        return isset($pat_array[1][0]) ? $pat_array[1][0] : '';
    }

    /**
     * 添加备注信息
     */
    public function addRemark()
    {
        $data['order_id'] = post('order_id');
        $data['remark'] = post('remark');
        $data['user_id'] = isession('user_id');
        $data['user_name'] = ssession('username');
        $data['truename'] = ssession('truename');
        post('isall') == 1 && $data['truename'] = "总公司-" . $data['truename'];
        $data['timestamp'] = time();
        Db::name('amazon_order_remark')->insert($data);
        $this->success("添加成功");
    }

    /**
     * 修改收货地址
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function address($id)
    {
        if (post()) {
            $data = post();
            unset($data['id']);
            Db::name('amazon_order')
                ->where('id', post('id'))
                ->update($data);
            $this->success('编辑成功');
        } else {
            $order = Db::name('amazon_order')
                ->where('id', $id)
                ->find();
            if (!checkArr($order)) {
                echo "当前订单不存在";
                die;
            }
            $this->assign('order', $order);
            $this->assign('nation', $this->getDictionary('nation'));
            return $this->fetch('address');
        }
    }

    /**
     * 更改订单状态
     */
    public function alter()
    {
        Db::name('amazon_order')
            ->where('id', post('id'))
            ->update(['order_status' => post('status')]);
        //更改订单下商品所有状态
        Db::name('amazon_order_goods')
            ->where('order_id', post('id'))
            ->update(['good_status' => post('status')]);
        //添加操作日志
        $data['order_id'] = post('id');
        $data['action'] = "将订单状态更改为" . $this->order_status[post('status')];
        $data['uid'] = isession('user_id');
        $data['user_name'] = ssession('username');
        $data['truename'] = ssession('truename');
        $data['order_status'] = post('status');
        $data['order_status_text'] = $this->order_status[post('status')];
        $data['action_time'] = time();
        Db::name('amazon_order_action')->insert($data);
        $this->success("更改成功");
    }

    /**
     * 更改订单中商品状态
     */
    public function alterGood()
    {
        $data = post();
        $where = " order_id =" . $data['order_id'] . " AND asin in ('" . join("','", $data['asin']) . "')";
        Db::name('amazon_order_goods')
            ->where($where)
            ->update(['good_status' => $data['status']]);
        //添加操作日志
        $insertData['order_id'] = $data['order_id'];
        $insertData['action'] = "将商品状态更改为" . $this->order_status[$data['status']];
        $insertData['uid'] = isession('user_id');
        $insertData['user_name'] = ssession('username');
        $insertData['truename'] = ssession('truename');
        $insertData['order_status'] = $data['status'];
        $insertData['order_status_text'] = $this->order_status[$data['status']];
        $insertData['action_time'] = time();
        Db::name('amazon_order_action')->insert($insertData);
        $this->success("更改成功");
    }

    /**
     * 添加找货单
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function lookGoodAdd()
    {
        if (post()) {
            $data = post();
            //获取订单下的商品信息
            $where = array(
                'order_id' => $data['order_id'],
                'asin' => $data['asin']
            );
            $order_goods = Db::name('amazon_order_goods')->where($where)->find();

            $insertData['guid'] = $order_goods['guid'];
            $insertData['order_id'] = $data['order_id'];
            $insertData['role_id'] = $data['role_id'];
            $insertData['num'] = $order_goods['num'];
            $insertData['user_id'] = $data['user_id'];
            $insertData['linkman'] = $data['linkman'];
            $insertData['title'] = $order_goods['goods_name'];
            $insertData['order_no'] = $order_goods['order_no'];
            $insertData['platform'] = 1;//亚马逊
            $insertData['shop_id'] = $data['shop_id'];
            $insertData['asin'] = $data['asin'];
            $insertData['url'] = $order_goods['url'];
            $insertData['remark'] = $data['remark'];
            $insertData['company_id'] = isession('company_id');
            $insertData['timestamp'] = time();
            Db::name('purchase')->insert($insertData);
            $find_goods_id = Db::name('purchase')->getLastInsID();
            //修改订单商品中的找货单
            Db::name('amazon_order_goods')->where($where)->update(['find_goods_id' => $find_goods_id, 'good_status' => 4]);
            $this->success("添加成功");
        } else {
            $this->assign('roles', $this->getRole());
            return $this->fetch('lookGoodAdd');
        }
    }

    /**
     * 找货单详情
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function lookGoodEdit()
    {
        if (post()) {
            $data = post();
            if ($data['company_id'] != isession('company_id') && $data['company_id'] != '') {
                $this->error("当前状态不允许编辑信息");
            }
            $updateDate['order_id'] = $data['order_id'];
            $updateDate['asin'] = $data['asin'];
            $updateDate['role_id'] = $data['role_id'];
            $updateDate['user_id'] = $data['user_id'];
            $updateDate['linkman'] = $data['linkman'];
            $updateDate['remark'] = $data['remark'];
            $updateDate['title'] = $data['title'];
            $updateDate['order_no'] = $data['order_no'];
            $updateDate['logistics'] = $data['logistics'];
            $updateDate['account_id'] = $data['account_id'];
            $updateDate['voucher'] = $data['voucher'];
            $updateDate['explain'] = $data['explain'];
            //更新找货信息
            Db::name('purchase')->where('id', $data['id'])->update($data);
            $this->success("修改成功");
        } else {
            $company_id = iget('company_id') ? iget('company_id') : isession('company_id');
            //查看订单下的商品详情
            $where = array(
                'order_id' => get('order_id'),
                'asin' => get('asin')
            );
            $goods = Db::name('amazon_order_goods')->where($where)->find();

            //找货单信息
            $find_good = $goods['find_goods_id'] ? Db::name('purchase')->where('id', $goods['find_goods_id'])->find() : [];
            //分配找货角色下的员工列表
            $user = $find_good['role_id'] ? $this->getUserList($find_good['role_id']) : [];
            //获取采购员下的支付账号
            $account = (isset($find_good['user_id']) && $find_good['user_id']) ? $this->getAccount($find_good['user_id']) : [];

            //查找店铺信息
            $store = DB::name('amazon_store')->where('id', get('shop_id'))->find();
            $this->assign('store', $store);

            $this->assign('goods', $goods);
            $this->assign('find_good', $find_good);
            $this->assign('user', $user);
            $this->assign('account', $account);
            $this->assign('roles', $this->getRole($company_id));
            $this->assign('unit', $this->getDictionary('unit'));
            return $this->fetch('lookGoodEdit');
        }
    }

    /**
     * 获取采购员信息
     */
    public function getUser()
    {
        $user = $this->getUserList(post('role_id'));
        echo json_encode($user);
    }

    /**
     * 获取采购员分配的支付账号信息
     */
    public function getUserAccount()
    {
        $account = $this->getAccount(post('user_id'));
        echo json_encode($account);
    }

    /**
     * 订单下的运单信息
     */
    public function waybill($id)
    {
        if (checkEntranceList()) {//总公司管理员，跳转选子公司页面
            action('admin/globalFun/choose', ['backtrack' => "waybill"]);
            return $this->fetch(APP_PATH . request()->module() . '/view/public/choose.html');
        }
        $where['company_id'] = iget('company_id') ? iget('company_id') : isession('company_id');
        $where['platform'] = 1;
        $where['order_id'] = $id;
        $waybill = Db::name('waybill')
            ->where($where)
            ->paginate(12);
        $this->assign('waybill', $waybill);
        return $this->fetch('waybill');
    }

    /**
     * 新建运单
     * @param $order_id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function waybillAdd($order_id)
    {
        if (post()) {
            $data = post();
            if (!isset($data['sku']) || count($data['sku']) == 0) {
                $this->error("请选择需要配送的产品");
            }
            //获取物流信息
            $logistics = $this->getLogisticsById($data['logistic_id']);
            if (!checkArr($logistics)) {
                $this->error("当前物流不存在");
            }
            //订单信息
            $order = Db::name('amazon_order')->where('id', $data['order_id'])->find();
            if (!checkArr($order)) {
                $this->error("当前订单不存在");
            }
            //手动方式，需要填写面单，追踪号
            if ($logistics['manual'] == 1) {
                empty($data['express']) && $this->error("当前物流下面单不能为空");
                empty($data['waybill']) && $this->error("当前物流不追踪号不能为空");
//                empty($data['fee']) && $this->error("当前物流不运费不能为空");
                $insertData['express'] = $data['express'];
                $insertData['waybill'] = $data['waybill'];
//                $insertData['fee_unit_id'] = $data['fee_unit_id'];
//                $insertData['fee_unit'] = $data['fee_unit'];
//                $insertData['fee'] = $data['fee'];
            } else {//提交数据，获取面单、追踪号
                //检测寄件人信息
                $shipper = DB::name('company_shipper')->find();
                if (!checkArr($shipper)) {
                    $this->error("寄件人信息不存在，请先添加寄件人信息");
                }

                $subfun = $logistics['subfun'];
                $logisticsModel = new LogisticsModel();
                $res = $logisticsModel->$subfun($logistics, $order, $data, $shipper);
                if ($res['status'] == false) {
                    $this->error($res['msg']);
                }
                $insertData['express'] = $res['data']['express'];
                $insertData['waybill'] = $res['data']['waybill'];
//                $insertData['fee_unit_id'] = $res['data']['fee_unit_id'];
//                $insertData['fee_unit'] = $res['data']['fee_unit'];
//                $insertData['fee'] = $res['data']['fee'];
            }
            //添加运单信息
            $insertData['fee_unit_id'] = $data['fee_unit_id'];
            $insertData['fee_unit'] = $data['fee_unit'];
            $insertData['fee'] = $data['fee'];

            //运费（人民币）
            $momey = 0;
            if ($data['fee'] > 0) {
                if ($data['fee_unit'] == 'CNY') {
                    $momey = $data['fee'];
                } else {
                    $rate = $this->getRate($data['fee_unit']);
                    $momey = $data['fee'] / $rate[$data['fee_unit']]['rate'];
                }
                $momey = cutNum($momey, 2);
            }
            $insertData['carriage'] = $momey;

            $insertData['order_id'] = $data['order_id'];
            $insertData['logistic'] = $data['logistic'];
            $insertData['logistic_id'] = $data['logistic_id'];
            $insertData['shipping_method'] = $data['shipping_method'];
            $insertData['customs'] = $data['customs'];
            $insertData['customs_en'] = $data['customs_en'];
            $insertData['coding'] = $data['coding'];
            $insertData['deliver'] = empty($data['deliver']) ? date("Y-m-d", time()) : $data['deliver'];
            $insertData['declare_unit_id'] = $data['declare_unit_id'];
            $insertData['declare_unit'] = $data['declare_unit'];
            $insertData['declare'] = $data['declare'];
            $insertData['insure_unit_id'] = $data['insure_unit_id'];
            $insertData['insure_unit'] = $data['insure_unit'];
            $insertData['insure'] = $data['insure'];
            $insertData['weight'] = $data['weight'];
            isset($data['is_battery']) && $insertData['is_battery'] = $data['is_battery'];
            $insertData['remark'] = $data['remark'];
            $insertData['platform'] = 1;
            $insertData['company_id'] = $data['company_id'] ? $data['company_id'] : isession('company_id');
            $insertData['timestamp'] = time();

            Db::name('waybill')->insert($insertData);
            $waybill_id = Db::name('waybill')->getLastInsID();
            //添加运单下的商品信息
            foreach ($data['sku'] as $key => $value) {
                $lang = $data['lang'][$value] ? $data['lang'][$value] : "moren";
                $goods[] = [
                    'waybill_id' => $waybill_id,
                    'sku' => $value,
                    'num' => $data['num'][$value],
                    'lang' => $lang,
                    'title' => $data['title'][$value],
                    'url' => $data['url'][$value],
                    'guid' => $data['guid'][$value],
                    'order_id' => $data['order_id']
                ];
            }
            Db::name("waybill_product")->insertAll($goods);
            //记录钱包日志
            $this->rechargeLog($data, $waybill_id);

            //总运费
            $updata['shipping_money'] = $momey + $order['shipping_money'];
            $updata['shipping_status'] = 3;
            //修改订单运单状态
            Db::name('amazon_order')->where('id', $data['order_id'])->update($updata);
            $this->success("创建成功");
        } else {
            if (checkEntranceAdd()) {
                $this->error("当前状态不允许添加信息");
            }
            //订单下的产品信息
            $orderGoods = Db::name('amazon_order_goods')
                ->where('order_id', $order_id)
                ->select();

            $this->assign('orderGoods', $orderGoods);
            //货币信息
            $this->assign('unit', $this->getDictionary('unit'));

            //物流公司信息
            $this->assign('logistics', $this->getLogistics());

            return $this->fetch('waybillAdd');
        }
    }

    /**
     * 运单详情
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function waybillEdit($id)
    {
        if (post()) {
            if (checkSubmitEdit()) {
                $this->error("当前状态不允许编辑信息");
            }
            $data = post();

            //订单信息
            $order = Db::name('amazon_order')->where('id', $data['order_id'])->find();
            if (!checkArr($order)) {
                $this->error("当前订单不存在");
            }
            $carriage = $data['carriage'];

            $updateData['logistic'] = $data['logistic'];
            $updateData['logistic_id'] = $data['logistic_id'];
            $updateData['shipping_method'] = $data['shipping_method'];
            $updateData['customs'] = $data['customs'];
            $updateData['customs_en'] = $data['customs_en'];
            $updateData['express'] = $data['express'];
            $updateData['coding'] = $data['coding'];
            $updateData['waybill'] = $data['waybill'];
            $updateData['deliver'] = empty($data['deliver']) ? date("Y-m-d", time()) : $data['deliver'];
            $updateData['declare_unit_id'] = $data['declare_unit_id'];
            $updateData['declare_unit'] = $data['declare_unit'];
            $updateData['declare'] = $data['declare'];
            $updateData['insure_unit_id'] = $data['insure_unit_id'];
            $updateData['insure_unit'] = $data['insure_unit'];
            $updateData['insure'] = $data['insure'];
            $updateData['fee_unit_id'] = $data['fee_unit_id'];
            $updateData['fee_unit'] = $data['fee_unit'];
            $updateData['fee'] = $data['fee'];
            $updateData['weight'] = $data['weight'];
            $updateData['is_battery'] = isset($data['is_battery']) ? $data['is_battery'] : 1;
            $updateData['remark'] = $data['remark'];

            //运费（人民币）
            $momey = 0;
            if ($data['fee'] > 0) {
                if ($data['fee_unit'] == 'CNY') {
                    $momey = $data['fee'];
                } else {
                    $rate = $this->getRate($data['fee_unit']);
                    $momey = $data['fee'] / $rate[$data['fee_unit']]['rate'];
                }
                $momey = cutNum($momey, 2);
            }
            $updateData['carriage'] = $momey;
            Db::name('waybill')->where('id', $data['id'])->update($updateData);
            if ($data['audit'] != 2) {
                $this->rechargeLog($data, $data['id']);
            }

            //总运费
            $updata['shipping_money'] = $momey + $order['shipping_money'] - $carriage;
            $updata['shipping_status'] = 3;
            //修改订单运单状态
            Db::name('amazon_order')->where('id', $data['order_id'])->update($updata);

            $this->success("更新成功");
        } else {
            //运单信息
            $waybill = Db::name('waybill')
                ->where('id', $id)
                ->find();
            //运单下的商品
            $waybillGoods = Db::name('waybill_product')
                ->where('waybill_id', $id)
                ->select();
            $this->assign('waybill', $waybill);
            $this->assign('waybillGoods', $waybillGoods);
            //货币信息
            $this->assign('unit', $this->getDictionary('unit'));
            //物流公司信息
            $logistics = arrayCombine($this->getLogistics(), 'id');
            $this->assign('logistics', $logistics);
            //配送方式
            $order = Db::name('amazon_order')->where('id', $waybill['order_id'])->find();
            if (!checkArr($order)) {
                $this->error('当前订单不存在');
            }
            $shipping = $this->getLogisticShips($waybill['logistic_id'], $order['receive_nation_short']);
            $this->assign('shipping', $shipping);

            return $this->fetch('waybillEdit');
        }
    }

    /**
     * 运单删除
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function waybillDel()
    {
        $data = post();
        if (checkArr($data['id'])) {
            $where = "id in ('" . join("','", $data['id']) . "')";
            $where1 = "waybill_id in ('" . join("','", $data['id']) . "')";
        } else {
            $where = "id = '" . $data['id'] . "'";
            $where1 = "waybill_id = '" . $data['id'] . "'";
        }
        //删除运单
        Db::name('waybill')->where($where)->delete();
        //删除运单下的产品
        Db::name('waybill_product')->where($where1)->delete();

        //删除运单对应的钱包扣款记录
        $this->delRechargeLog($data);

        $this->success("删除成功");
    }

    /**
     * 获取快递公司服务列表
     */
    public function getLogisticShip()
    {
        //订单信息
        $order = Db::name('amazon_order')->where('id', post('order_id'))->find();
        if (!checkArr($order)) {
            echo json_encode(['status' => false, 'msg' => "当前订单不存在"]);
            die;
        }
        $service = $this->getLogisticShips(post('logistics_id'), $order['receive_nation_short']);
        if (checkArr($service)) {
            echo json_encode(['status' => true, 'data' => $service]);
            die;
        }
        echo json_encode(['status' => false, 'msg' => "当前物流暂无收件人国家货运方式"]);
        die;
    }

    /**
     * 更新当前订单状态
     * @param $id
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function updateOrder($id)
    {
        //订单信息
        $order = Db::name('amazon_order')
            ->where('id', $id)
            ->find();
        if (!checkArr($order)) {
            echo "当前订单不存在";
            die;
        }
        //查找店铺信息
        $store = DB::name('amazon_store')->where('id', $order['shop_id'])->find();
        //更新当前订单状态
        $params = array(
            'AWSAccessKeyId' => $store['aws_access_key'],
            'Action' => "GetOrder",
            'SellerId' => $store['seller_id'],
            'SignatureMethod' => "HmacSHA256",
            'SignatureVersion' => "2",
            'Timestamp' => gmdate("Y-m-d\TH:i:s\Z", time()),
            'Version' => "2013-09-01",
            'AmazonOrderId.Id.1' => $order['order_no']
        );
        $url_parts = array();
        foreach (array_keys($params) as $key) {
            $url_parts[] = $key . "=" . str_replace('%7E', '~', rawurlencode($params[$key]));
        }

        sort($url_parts);
        $url_string = implode("&", $url_parts);
        $string_to_sign = "GET\nmws.amazonservices.in\n/Orders/2013-09-01\n" . $url_string;

        $signature = hash_hmac("sha256", $string_to_sign, $store['secret_key'], TRUE);

        $signature = urlencode(base64_encode($signature));

        $url = "https://mws.amazonservices.in/Orders/2013-09-01" . '?' . $url_string . "&Signature=" . $signature;
        $content = request_get($url);
        if ($content == '') {
            $this->error('获取超时，请重试');
        }
        //获取商品
        $orderGoods = xmlToArray($content);

        switch ($orderGoods['GetOrderResult']['Orders']['Order']['OrderStatus']) {
            case "PendingAvailability":
                $order_status = 1;
                break;
            case "Pending":
                $order_status = 1;
                break;
            case "Unshipped":
                $order_status = 7;
                break;
            case "PartiallyShipped":
                $order_status = 8;
                break;
            case "Shipped":
                $order_status = 8;
                break;
            case "InvoiceUnconfirmed":
                $order_status = 9;
                break;
            case "Canceled":
                $order_status = 2;
                break;
            case "Unfulfillable":
                $order_status = 6;
                break;
            default:
                $order_status = 3;
                break;
        }

        Db::name('amazon_order')->where('id', $id)->update(['order_status' => $order_status]);
        $this->success("更新成功");
    }

    /**
     * 批量真假发货
     */
    public function deliver()
    {
        $data = post();
        $id = $data['id'];
        $shop_id = $data['shop_id'];
        $store = DB::name('amazon_store')->where('id', $shop_id)->find();

        $where['order_id'] = checkArr($id) ? ['in', join(",", $id)] : $id;
        $whereOrder['id'] = $where['order_id'];
        $whereOrder['is_good'] = 2;
        if ($data['type'] == 1) {//假发货
            //获取订单下的商品信息
            $orderGood = Db::name('amazon_order_goods')->where($where)->select();
            if (count($orderGood) == 0) {
                $this->error('该订单暂未抓取过详情商品');
            }

            //查找订单信息
            $orders = Db::name('amazon_order')
                ->field('id,order_no,earliest_ship_time,latest_ship_time,delivery_time,is_good')
                ->where($whereOrder)
                ->select();
            $orders = arrayCombine($orders, 'id');

            $xml = '';
            $i = 0;
            $order_id = [];
            foreach ($orderGood as $key => $value) {
                //组装XML
                $i++;
                if (isset($orders[$value['order_id']])) {
                    $xml .= $this->putPhonyXml($orders[$value['order_id']], $value, $i);
                    $order_id[] = $value['order_id'];
                }
            }
            if ($xml && count($order_id) > 0) {
                $this->updateWaybill($xml, $store);
                Db::name('amazon_order')->where(['id' => ['in', $order_id]])->update(['fake_good_time' => time()]);
                $this->success("假发货成功");
            } else {
                $this->error("假发货失败");
            }
        } else {
            //获取订单下的运单信息
            $waybills = DB::name('waybill')->where($where)->select();
            if (count($waybills) == 0) {
                $this->error('该订单暂未填写运单信息');
            }
            $waybills = arrayCombine($waybills, 'id');
            $waybill_id = array_column($waybills, 'id');
            //获取运单下产品信息
            $whereWaybill['waybill_id'] = ['in', join(',', $waybill_id)];
            $whereWaybill['order_id'] = $where['order_id'];
            $waybillGood = DB::name('waybill_product')->where($whereWaybill)->select();
            if (count($waybillGood) == 0) {
                $this->error('该订单下的运单中暂未发货');
            }
            //查找订单信息
            $orders = Db::name('amazon_order')
                ->field('id,order_no,earliest_ship_time,latest_ship_time,delivery_time,is_good')
                ->where($whereOrder)
                ->select();
            $orders = arrayCombine($orders, 'id');
            $xml = '';
            $i = 0;
            $order_id = [];
            foreach ($waybillGood as $key => $value) {
                //组装XML
                $i++;
                if (isset($orders[$value['order_id']]) && isset($waybills[$value['waybill_id']])) {
                    $xml .= $this->putRealXml($orders[$value['order_id']], $waybills[$value['waybill_id']], $value, $i);
                    $order_id[] = $value['order_id'];
                }
            }
            if ($xml && count($order_id) > 0) {
                $this->updateWaybill($xml, $store);
                Db::name('amazon_order')->where(['id' => ['in', $order_id]])->update(['true_good_time' => time()]);
                $this->success("真发货成功");
            } else {
                $this->error("真发货失败");
            }
        }
    }

    /**
     * 组装假发货运单xml
     * @param $orders
     * @param $orderGood
     * @param $i
     * @return string
     */
    public function putPhonyXml($orders, $orderGood, $i)
    {
        if ($orders['earliest_ship_time'] < time() && $orders['latest_ship_time'] > time()) {
            $time = time();
        } elseif ($orders['earliest_ship_time'] < $orders['delivery_time'] && $orders['latest_ship_time'] > $orders['delivery_time']) {
            $time = $orders['delivery_time'];
        } else {
            $time = intval(floor(($orders['latest_ship_time'] - $orders['earliest_ship_time']) / 2)) + $orders['earliest_ship_time'];
        }
        $xml = "<Message>
           <MessageID>" . $i . "</MessageID>
           <OrderFulfillment>
           <AmazonOrderID>" . $orderGood['order_no'] . "</AmazonOrderID>
           <FulfillmentDate>" . gmdate("Y-m-d\TH:i:s\Z", $time) . "</FulfillmentDate>
           <FulfillmentData>
           <CarrierName>Other</CarrierName>
           <ShippingMethod>Standard</ShippingMethod>
           <ShipperTrackingNumber>" . getNumString() . "</ShipperTrackingNumber>
           </FulfillmentData>
           <Item>
            <AmazonOrderItemCode>" . $orderGood['order_item_id'] . "</AmazonOrderItemCode>
            <Quantity>1</Quantity>
           </Item>
          </OrderFulfillment>
          </Message>";
        return $xml;
    }

    /**
     * 组装真发货运单xml
     * @param $orders
     * @param $waybill
     * @param $waybillGood
     * @param $i
     * @return string
     */
    public function putRealXml($orders, $waybill, $waybillGood, $i)
    {
        if ($orders['earliest_ship_time'] < time() && $orders['latest_ship_time'] > time()) {
            $time = time();
        } elseif ($orders['earliest_ship_time'] < $orders['delivery_time'] && $orders['latest_ship_time'] > $orders['delivery_time']) {
            $time = $orders['delivery_time'];
        } else {
            $time = intval(floor(($orders['latest_ship_time'] - $orders['earliest_ship_time']) / 2)) + $orders['earliest_ship_time'];
        }
        $xml = "<Message>
           <MessageID>" . $i . "</MessageID>
           <OrderFulfillment>
           <AmazonOrderID>" . $orders['order_no'] . "</AmazonOrderID>
           <FulfillmentDate>" . gmdate("Y-m-d\TH:i:s\Z", $time) . "</FulfillmentDate>
           <FulfillmentData>
           <CarrierName>Other</CarrierName>
           <ShippingMethod>" . $waybill['shipping_method'] . "</ShippingMethod>
           <ShipperTrackingNumber>" . $waybill['waybill'] . "</ShipperTrackingNumber>
           </FulfillmentData>
           <Item>
            <AmazonOrderItemCode>" . $waybillGood['sku'] . "</AmazonOrderItemCode>
            <Quantity>" . $waybillGood['num'] . "</Quantity>
           </Item>
          </OrderFulfillment>
          </Message>";
        return $xml;
    }

    /**
     * 更改运单信息
     */
    public function updateWaybill($xml, $store)
    {
        $xml_string = '<?xml version="1.0" encoding="UTF-8"?>
         <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
          <Header>
           <DocumentVersion>1.01</DocumentVersion>
           <MerchantIdentifier>' . $store['seller_id'] . '</MerchantIdentifier>
          </Header>
          <MessageType>OrderFulfillment</MessageType>';
        $xml_string .= $xml;
        $xml_string .= '</AmazonEnvelope>';
        $var = base64_encode(md5(trim($xml_string), true));

        $param = array(
            'AWSAccessKeyId' => $store['aws_access_key'],
            'Action' => "SubmitFeed",
            'FeedType' => "_POST_ORDER_FULFILLMENT_DATA_",
            'MarketplaceIdList.Id.1' => $store['marketplace'],
            'Merchant' => $store['seller_id'],
            'ContentMD5Value' => $var,
            'FeedContent' => trim($xml_string),
            'SignatureMethod' => "HmacSHA256",
            'SignatureVersion' => "2",
            'Timestamp' => gmdate("Y-m-d\TH:i:s\Z", time()),
            'Version' => "2009-01-01",
            'PurgeAndReplace' => 'false'
        );

        $url = array();
        foreach ($param as $key => $val) {

            $key = str_replace("%7E", "~", rawurlencode($key));
            $val = str_replace("%7E", "~", rawurlencode($val));
            $url[] = "{$key}={$val}";
        }

        sort($url);

        $arr = implode('&', $url);

        $sign = 'POST' . "\n";
        $sign .= 'mws.amazonservices.in' . "\n";
        $sign .= '/Feeds/2009-01-01' . "\n";
        $sign .= $arr;

        $signature = hash_hmac("sha256", $sign, $store['secret_key'], true);
        $signature = urlencode(base64_encode($signature));

        $link = "https://mws.amazonservices.in/Feeds/2009-01-01?";
        $link .= $arr . "&Signature=" . $signature;

        $headers = array(
            'Content-Type: application/xml',
            'Content-Length: ' . strlen($xml_string),
            'Content-MD5: ' . $var
        );
        $ch = curl_init($link);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_string);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        $content = curl_exec($ch);

        if ($content == '') {
            $this->error('获取超时，请重试');
        }
        //写入日志
        $file = server("DOCUMENT_ROOT") . "/runtime/log/yundan.log";
        file_put_contents($file, "\r\n********************** " . date('Y-m-d H:i:s', time()) . " **********************************\r\n", FILE_APPEND);
        file_put_contents($file, $content, FILE_APPEND);
        return true;
    }

    /**
     * 运单记录钱包日志
     * @param array $data
     * @param string $waybill_id
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function rechargeLog($data = [], $waybill_id = '')
    {
        $company_id = isession('company_id');
        $type = isession('type');
        $purpose = $type == 1 ? 1 : 2;
        //检测充值公司钱包是否存在
        $where['company_id'] = $company_id;
        $where['purpose'] = $purpose;
        $wallet = DB::name('wallet')->where($where)->find();
        if (!checkArr($wallet)) {//不存在钱包，创建空钱包
            $insertData['money'] = 0;
            $insertData['company_id'] = $company_id;
            $insertData['type'] = $type;
            $insertData['purpose'] = $purpose;
            $insertData['timestamp'] = time();
            DB::name('wallet')->insert($insertData);
            $wallet_id = Db::name('wallet')->getLastInsID();
        } else {
            $wallet_id = $wallet['id'];
        }


        $money = $data['fee'];
        //不是人民币，需要换算单位
        if ($data['fee_unit'] != 'CNY') {
            $money = $this->toCny($money, $data['fee_unit']);
        }
        $log['money'] = $money;
        $log['remark'] = $data['remark'];

        $where1['detail_id'] = $waybill_id;
        $where1['project'] = 4;
        $where1['purpose'] = $purpose;
        $where1['operate'] = 2;
        $where1['audit'] = 1;
        $wallet_log = DB::name('wallet_log')->where($where1)->find();
        if (checkArr($wallet_log)) {//存在记录，更新
            DB::name('wallet_log')->where('id', $wallet_log['id'])->update($log);
            return true;
        }

        $log['wallet_id'] = $wallet_id;
        $log['company_id'] = $company_id;
        $log['type'] = $type;
        $log['purpose'] = $purpose;
        $log['operate'] = 2;
        $log['operate_company_id'] = $company_id;
        $log['operate_date'] = time();
        $log['reason_id'] = '';
        $log['reason'] = '运单运费';
        $log['resource_id'] = '';
        $log['project'] = 4;
        $log['detail_id'] = $waybill_id;
        $log['audit'] = 1;
        $log['operate_audit'] = 1;
        $log['operate_uid'] = isession('user_id');
        $log['operate_name'] = ssession('username');
        $log['operate_truename'] = ssession('truename');
        $log['timestamp'] = time();
        DB::name('wallet_log')->insert($log);
    }

    /**
     * 外汇换算人民币
     * @param int $money
     * @param string $unit
     * @return float|int
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function toCny($money = 0, $unit = '')
    {
        if ($money == 0 || $unit == '') {
            return 0;
        }
        $rate = $this->getCNY($unit, $type = 'update');
        return $money / $rate;
    }

    /**
     * 删除钱包运单扣款记录
     * @param $waybill_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function delRechargeLog($waybill_id)
    {
        $company_id = isession('company_id');
        $purpose = 2;
        //检测充值公司钱包是否存在
        $where['company_id'] = $company_id;
        $where['purpose'] = $purpose;
        $wallet = DB::name('wallet')->where($where)->find();
        if (!checkArr($wallet)) {//不存在钱包
            return false;
        }

        if (checkArr($waybill_id['id'])) {
            $where1['detail_id'] = ['in', join("','", $waybill_id['id'])];
        } else {
            $where1['detail_id'] = $waybill_id['id'];
        }

        $where1['project'] = 4;
        $where1['purpose'] = $purpose;
        $where1['operate'] = 2;
        $where1['audit'] = 1;
        DB::name('wallet_log')->where($where1)->delete();
        return true;
    }

    /**
     * 修改手续费
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function editfee()
    {
        $order = Db::name('amazon_order')->where('id', ipost('id'))->find();
        if (!checkArr($order)) {
            $this->error('当前订单不存在！');
        }

        if ($order['coin'] == 'CNY') {
            $fee = post('fee');
            $expend_fee = $fee;
            $profit = $order['profit'] - $expend_fee;
        } else {
            $fee = post('fee');
            $expend_fee = $order['rate'] == 0 ? $this->toCny($fee, $order['coin']) : $fee / $order['rate'];
            $profit = $order['profit'] - $expend_fee;
        }
        $updateData['fee'] = $fee;
        $updateData['expend_fee'] = $expend_fee;
        $updateData['profit'] = $profit;
        Db::name('amazon_order')->where('id', ipost('id'))->update($updateData);
        $this->success('修改成功');
    }

    /************************************  总公司运单 **********************************************************************/

    /**
     * 待发货亚马逊列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function amazonDelivery()
    {
        $where['shipping_status'] = 2;
        $where1 = [];
        $product = [];

        //订单编号
        get('order_no') && $where['order_no'] = ['like', '%' . get('order_no') . '%'];
        get('order_status') && $where['order_status'] = get('order_status');
        get('start') && $where1['create_time'] = ['>=', strtotime(get('start') . " 00:00:00")];
        get('end') && $where['create_time'] = ['<=', strtotime(get('end') . " 23:59:59")];
        $data = Db::name('amazon_order')
            ->where($where)
            ->where($where1)
            ->order('create_time desc')
            ->paginate(30, false, ['query' =>
                [
                    'order_no' => get('order_no'),
                    'order_status' => get('order_status'),
                    'start' => get('start'),
                    'end' => get('end')
                ]]);

        $list = $data->all();
        if (checkArr($list)) {
            //获取所有订单id
            $order_ids = array_column($list, 'id');

            //获取订单下有图片url的商品
            $where2['url'] = ['neq', ''];
            $where2['order_id'] = ['in', join(',', $order_ids)];
            $product = Db::name('amazon_order_goods')
                ->field('order_id,url')
                ->where($where2)
                ->group('order_id')
                ->select();
            checkArr($product) && $product = arrayCombine($product, 'order_id');
        }

        //获取全部店铺信息
        $store = DB::name('amazon_store')->field('id,nation_short,nation')->select();
        checkArr($store) && $store = arrayCombine($store, 'id');
        $this->assign('store', $store);
        $this->assign('product', $product);
        $this->assign('orders', $data);
        return $this->fetch('amazonDelivery');
    }

    /**
     * 亚马逊订单详情
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function amazonInfoDelivery($id)
    {
        //订单信息
        $order = Db::name('amazon_order')
            ->where('id', $id)
            ->find();
        if (!checkArr($order)) {
            $this->error('当前订单不存在');
        }

        //订单下的产品信息
        $orderGoods = Db::name('amazon_order_goods')
            ->where('order_id', $id)
            ->select();

        //查找订单备注信息
        $orderRemarks = Db::name('amazon_order_remark')
            ->where('order_id', $id)
            ->order(['timestamp' => 'desc'])
            ->select();
        //获取订单操作日志
        $orderAction = Db::name('amazon_order_action')
            ->where('order_id', $id)
            ->order(['action_time' => 'desc'])
            ->select();

        $this->assign('store', DB::name('amazon_store')->where('id', $order['shop_id'])->find());

        $this->assign('order_status', $this->order_status);
        $this->assign('order', $order);
        $this->assign('orderGoods', $orderGoods);
        $this->assign('orderRemarks', $orderRemarks);
        $this->assign('orderAction', $orderAction);
        return $this->fetch('amazonInfoDelivery');
    }


}
